import 'dart:convert';

import 'package:demo/qiyu_order.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';

import 'http/api_response.dart';
import 'http/http.dart';

part 'flutter_bridge.dart';

class BrowserPage extends StatefulWidget {
  const BrowserPage({this.arguments, super.key});

  final dynamic arguments;

  @override
  State<StatefulWidget> createState() => BrowserPageState();
}

class BrowserPageState extends State<BrowserPage> {
  late String title;
  late String url;
  late String data;
  late final FlutterBridge _flutterBridge = FlutterBridge(context, () async {}, onClosePressed: () {}, hideAccUsePressed: () {});

  final String htmlContent = '''
<p><strong>出品：科普中国</strong></p>\n<p><strong>作者：王鑫（中国科学院南京地质古生物研究所）</strong></p>\n<p><strong>监制：中国科普博览</strong></p>\n<p>
<strong>编者按：为揭开科技工作的神秘面纱，科普中国前沿科技项目推出“我和我的研究”系列文章，邀请科学家亲自执笔，分享科研历程，打造科学世界。让我们跟随站在科技最前沿的探索者们，开启一段段充满热情、挑战与惊喜的旅程。</strong>
</p>\n<p>
被子植物是当今世界上多样性最高的类群，至少有30万种。我们人类的衣食住行医很大程度上都不得不依靠被子植物，比如我们每天要吃的主食和蔬菜，绝大部分都是被子植物。其实，早在人类起源的几百万年前，被子植物就已经是地球生态系统不可或缺的重要成分了。
</p> ''';

  @override
  void initState() {
    super.initState();
    title = widget.arguments?["title"] ?? "";
    url = widget.arguments?["url"] ?? "";
    data = widget.arguments?["data"] ?? "";
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text(title)),
      backgroundColor: Colors.white,
      body: Padding(padding: const EdgeInsets.only(left: 20, right: 20), child: otherWidget()),
    );
  }

  late InAppWebViewController _webViewController;

  late bool hasFollow;

  Widget appWidget() {
    return InAppWebView(
        // initialUrlRequest: url.isEmpty ? null : URLRequest(url: WebUri(url)),
        initialData: data.isEmpty ? null : InAppWebViewInitialData(data: data),
        initialSettings: InAppWebViewSettings(
            allowContentAccess: true,
            clearCache: true,
            useShouldOverrideUrlLoading: true,
            overScrollMode: OverScrollMode.NEVER,
            domStorageEnabled: true,
            javaScriptEnabled: true),
        onWebViewCreated: (controller) {
          _flutterBridge.addJavaScriptHandler(controller);
        },
        shouldOverrideUrlLoading: (InAppWebViewController controller, NavigationAction navigationAction) async {
          var url = navigationAction.request.url;
          debugPrint("shouldOverrideUrlLoading()--url:$url");
          return NavigationActionPolicy.ALLOW;
        },
        onLoadStart: (_, url) {
          debugPrint("onPageStarted():$url");
        },
        onLoadStop: (_, __) {
          debugPrint("onPageFinished()");
        },
        onProgressChanged: (_, progress) {
          debugPrint("onProgress()--$progress");
          if (progress == 100) {
            setState(() {});
          }
        },
        onReceivedError: (InAppWebViewController controller, WebResourceRequest request, WebResourceError error) {
          debugPrint("onWebResourceError()--$error");
        },
        onConsoleMessage: (_, consoleMessage) {
          debugPrint("onConsoleMessage()--$consoleMessage");
        });
  }

  Widget otherWidget() {
    return Stack(children: [
      InAppWebView(
// initialUrlRequest: URLRequest(url: WebUri.uri(Uri.parse(widget.url))),
          initialSettings: InAppWebViewSettings(
            verticalScrollBarEnabled: false,
            horizontalScrollBarEnabled: false,
            supportZoom: false,
            disableContextMenu: false,
// 插件 bug 无法禁用
            applicationNameForUserAgent: 'Android HarmonyOS scienceChina/8.9.0',
          ),
          onWebViewCreated: (controller) {
            _webViewController = controller;
            _loadContent();
          },
          onLoadStop: (InAppWebViewController controller, Uri? url) async {
// 获取 WebView 内容的高度
            String heightStr = await controller.evaluateJavascript(source: "document.documentElement.scrollHeight.toString()");
            debugPrint(heightStr);
          })
    ]);
  }

  void _loadContent() {
    if (data.isNotEmpty) {
      _webViewController.loadData(
        data: data,
        mimeType: 'text/html',
        encoding: 'utf-8',
      );
    } else {
      _webViewController.loadUrl(urlRequest: URLRequest(url: WebUri.uri(Uri.parse(url))));
    }

    // InAppWebViewController.setWebContentsDebuggingEnabled(true);
  }
}
